package com.unhz.taigu.service.impl;

import com.unhz.generator.dao.KeyMapper;
import com.unhz.generator.dao.SysRolePermissionMapper;
import com.unhz.generator.dao.UserDictMapper;
import com.unhz.generator.dao.UserMapper;
import com.unhz.generator.enums.EnumStatus;
import com.unhz.generator.enums.EnumValid;
import com.unhz.generator.pojo.*;
import com.unhz.generator.utils.EmptyUtil;
import com.unhz.generator.utils.IsNumeric;
import com.unhz.generator.utils.MD5;
import com.unhz.generator.utils.Page;
import com.unhz.generator.vo.UserVo;
import com.unhz.taigu.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.text.Keymap;
import java.util.*;

/**
 * @Author: 沈佳庆
 * @Description:
 * @Date: Created in 下午 2:50 2018/1/24 0024
 * @Modified By:
 */
@Service
public class UserServiceImpl implements UserService{

    private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ProductionRangeService productionRangeService;
    @Autowired
    private AreaDictService areaDictService;
    @Autowired
    private SysRolePermissionMapper sysRolePermissionMapper;
    @Autowired
    private KeyMapper keyMapper;

    @Override
    public Page<User> selectPageUser(String pageNo, Integer pageSize, String keywords,Integer adminId,Integer roleId) {
        int pageNum = 1;
        boolean numok = IsNumeric.isNumeric(pageNo);
        if(numok){
            if(pageNo !=null && !"".equals(pageNo)){
                pageNum = Integer.parseInt((pageNo));
            }
        }
        //查询roleId中是否存在permissionId对应值的权限
        int count = sysRolePermissionMapper.selectPermissionIdByRoleIdUser(roleId);
        //获取记录总条数
        int totalRecords = 0;
        if(1==count){
            totalRecords = userMapper.getTotalRecordsByKeywords(keywords);
        }else{
            totalRecords = userMapper.getTotalRecordsByKeywordsAndAdminId(keywords,adminId);
        }
        Page page = new Page(pageNum,totalRecords);
        page.setPageSize(pageSize);
        Map<String ,Object> map = new HashMap<String,Object>();
        map.put("startIndex",page.getStartIndex());
        map.put("pageSize",page.getPageSize());
        map.put("keywords",keywords);
        map.put("adminId",adminId);
        //获取总记录数
        List<UserVo> records = new ArrayList<UserVo>();
        if(1==count){
            records = userMapper.findUserMap(map);
        }else{
            records = userMapper.findUserMapByAdminId(map);
        }
        for(UserVo userVo:records){
            String companyProvince = areaDictService.findAreaNameByProvince(userVo.getCompanyProvince()).getName();
            String companyCity = areaDictService.findAreaNameByCity(userVo.getCompanyCity()).getName();
            String companyCounties = null;
            if("0".equals(userVo.getCompanyCounties())){
                companyCounties = "";
            }else{
                companyCounties = areaDictService.findAreaNameByCountry(userVo.getCompanyCounties()).getName();
            }

            String companyAddress = null;
            if(userVo.getCompanyProvince().equals(userVo.getCompanyCity())){
                companyAddress = companyProvince+companyCounties+userVo.getCompanyAddress();
            }else{
                companyAddress = companyProvince+companyCity+companyCounties+userVo.getCompanyAddress();
            }
            String storageProvince = areaDictService.findAreaNameByProvince(userVo.getStorageProvince()).getName();
            String storageCity = areaDictService.findAreaNameByCity(userVo.getStorageCity()).getName();
            String storageCounties = null;
            if("0".equals(userVo.getStorageCounties())){
                storageCounties = "";
            }else{
                storageCounties = areaDictService.findAreaNameByCountry(userVo.getStorageCounties()).getName();
            }
            String storageAddress = null;
            if(userVo.getStorageProvince().equals(userVo.getStorageCity())){
                storageAddress = storageProvince+storageCounties+userVo.getStorageAddress();
            }else{
                storageAddress = storageProvince+storageCity+storageCounties+userVo.getStorageAddress();
            }
            userVo.setCompanyAddress(companyAddress);
            userVo.setStorageAddress(storageAddress);
            logger.info(userVo.getStatus());
        }
        page.setRecords(records);
        String uri = "/user/findAllUser?keywords="+keywords+"&roleId="+roleId+"&adminId="+adminId;
        page.setUri(uri);
        return page;
    }

    @Override
    public  User findLongUser(String userPhone,String userPassword )
    {
        return userMapper.findLongUser(userPhone,userPassword);
    }


    @Override
    public void deleteById(Integer userId) {
        userMapper.deleteById(userId);
    }

    @Override
    public UserVo findUserById(Integer userId) {
        UserVo userVo = userMapper.findUserById(userId);
        String storageAddress = userVo.getStorageProvince()+userVo.getStorageCity()+userVo.getStorageCounties()+userVo.getStorageAddress();
        String companyAddress =  userVo.getCompanyProvince()+userVo.getCompanyCity()+userVo.getCompanyCounties()+userVo.getCompanyAddress();
        userVo.setCompanyAddress(companyAddress);
        userVo.setStorageAddress(storageAddress);
        return userVo;
    }

    @Override
    public List<User> selectAllUser() {
        return userMapper.selectAllUser();
    }

    @Override
    public UserVo findUser(String userName) {
        UserVo userVo = userMapper.selectByUserName(userName);
        return userVo;
    }

    @Override
    public int insert(User user) {
        return userMapper.insertSelective(user);
    }

    @Override
    public String updateIsenable(Integer userId, Integer isenable, String adminName) {
        //修改用户的禁用启用状态
        User user = new User();
        user.setId(userId);
        user.setStatus(EnumStatus.CHECKING.getIndex());
        user.setUpdateBy(adminName);
        int count = userMapper.updateByPrimaryKeySelective(user);
        if( count > 0){
            return "success";
        }
        return "failed";
    }

    @Override
    public String updateExamine(Integer userId, Integer examine, String adminName) {
        //修改用户的禁用启用状态
        User user = userMapper.selectByPrimaryKey(userId);
        Integer valid = user.getValid();
        if(examine == EnumValid.FIRST_ENABLED.getIndex()){
            switch (valid){
                case 0:
                    valid = EnumValid.ENABLED.getIndex();
                    break;
                case 1:
                    valid = EnumValid.DISABLE.getIndex();
                    break;
                case 2:
                    valid = EnumValid.ENABLED.getIndex();
                    break;
            }
        }
        user.setValid(valid);
        user.setStatus(examine);
        user.setCheckBy(adminName);
        user.setCheckTime(new Date());
        int count = userMapper.updateByPrimaryKeySelective(user);
        if( count > 0){
            return "success";
        }
        return "failed";
    }

    @Override
    public UserVo findUserUpdateById(Integer userId) {
        return userMapper.findUserById(userId);
    }

    @Override
    public int updateUser(User user,String type) {
        int flag=0;
        String updater="";
        if(!EmptyUtil.isEmpty(user)) {
           user.setUserName(user.getUserName().replaceAll(" ", ""));
           user.setUserPhone(user.getUserPhone().replaceAll(" ",""));
           SysUser sysUser=sysUserService.selectByUserId(user.getAdminId());
           if(!EmptyUtil.isEmpty(sysUser)){
               updater=sysUser.getUserName();
           }
           user.setUpdateBy(updater);
           user.setUpdateTime(new Date());
           user.setCompanyProvince(user.getCompanyProvince().replaceAll(" ", ""));
            user.setCompanyCity(user.getCompanyCity().replaceAll(" ", ""));
            if(null!=user.getCompanyCounties()) {
                user.setCompanyCounties(user.getCompanyCounties().replaceAll(" ", ""));
            }
            user.setCompanyAddress(user.getCompanyAddress().replaceAll(" ", ""));
            user.setStorageProvince(user.getStorageProvince().replaceAll(" ", ""));
            user.setStorageCity(user.getStorageCity().replaceAll(" ", ""));
            if(null!=user.getStorageCounties()) {
                user.setStorageCounties(user.getStorageCounties().replaceAll(" ", ""));
            }
            user.setStorageAddress(user.getStorageAddress().replaceAll(" ", ""));
            user.setStatus(1);  //'审核状态：1.审核中 2.审核通过 3.审核不通过 ',
            // 修改生产范围
            Integer id = user.getId();
            String [] strs = type.split(",");
            ProductionRange productionRange = null;
            //先删除之前的生产范围
            productionRangeService.deleteByUserId(id);
            //添加生产范围
            for(int i=0,len=strs.length;i<len;i++){
                productionRange = new ProductionRange();
                productionRange.setUserId(id);
                productionRange.setCreateTime(new Date());
                productionRange.setProductionRange(strs[i]);
                productionRangeService.insert(productionRange);
            }
            userMapper.updateByPrimaryKeySelective(user);
            return 1;
        }
        return 0;
    }

    @Override
    public User selectById(Integer userId) {
        return userMapper.selectById(userId);
    }

    public User selectUserById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);

    }

    @Override
    public void keyPass(User user) {
        userMapper.keyPass(user);
    }

    @Override
    public User selectByPrimaryKey(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public List<UserVo> findAllUser(String administratorName) {
        return userMapper.selectUserImportExport(administratorName);
    }

    @Override
    public User findUserPhone(String userPhone) {
        return userMapper.findUserPhone(userPhone);
    }

    @Override
    public int updatePhone(User u) {
        return userMapper.updatePhone(u);
    }
}
